package com.dayilyword.controller;

import com.dayilyword.config.resultFormat.Result;
import com.dayilyword.config.resultFormat.ResultFormat;
import com.dayilyword.entity.SysUser;
import com.dayilyword.entity.User;
import com.dayilyword.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * <p>>@作者 Sc
 * <p>>@所属包 dayilyword:com.dayilyword.controller
 * <p>>@创建时间 2020-11-13-12-46
 * <p>>@功能描述
 **/
@RestController
@RequestMapping("user")
@Api(tags = "用户")
public class UserController {
    private final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;

    /**
     * 注册
     *
     * @param
     * @return
     */
    @PostMapping("/reg")
    @ResponseBody
    @ApiOperation("注册")
    public Result reg(SysUser sysUser) {
        if (userService.loginSql(sysUser.getPhone(), null) == null) {
            RandomNumberGenerator rng = new SecureRandomNumberGenerator();
            String salt = rng.nextBytes().toHex();
            User user = new User();
            user.setPhone(sysUser.getPhone());
            //加密方式
            String hashAlgorithmName = "MD5";
            //密码原值
            Object crdentials = sysUser.getPwd();
            //加密3次
            int hashIterations = 3;
            String result = String.valueOf(new SimpleHash(hashAlgorithmName, crdentials, salt, hashIterations));
            user.setNiceName(sysUser.getNiceName());
            user.setPwd(result);
            user.setSalt(salt);
            user.setCreate_time(System.currentTimeMillis());
            userService.insertSelective(user);
            return ResultFormat.ok("success");
        } else {
            return ResultFormat.ok("Have_Phone");
        }
    }

    @GetMapping("loginout")
    @ApiOperation("登出")
    public String loginout() {
        SecurityUtils.getSubject().logout();// 将用户移除shiro
        return "tologin";
    }

    /**
     *
     * 近期发布信息
     */
    /**
     * 登录 返回个人信息
     * 返回关注数  粉丝数 状态 昵称 个性签名
     *
     * @return
     */
    @GetMapping("/login")
    @ResponseBody
    @ApiOperation("登录 返回个人信息")
    public Result login(SysUser sysUser, HttpServletRequest request) {
        String result="";
        Subject currentUser = SecurityUtils.getSubject();

        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(sysUser.getPhone(), sysUser.getPwd());
            try {
                //登录，进行密码比对，登录失败时将会抛出对应异常
                currentUser.login(usernamePasswordToken);
                result = "登录成功";
            } catch (UnknownAccountException uae) {
                result = "用户名不存在";
            } catch (IncorrectCredentialsException ice) {
                result = "密码错误";
            } catch (LockedAccountException lae) {
                result = "用户状态异常";
            } catch (AuthenticationException ae) {
                result = "登录失败，请与管理员联系";

            }
            logger.info(result);
            if (!"登录成功".equals(result)) {
                return ResultFormat.ok(request);
            }
        }


  /*      User user = new User();
        if (sysUser.getLoginType() == 1) {
            user.setUnionid_HW(sysUser.getUnionid());
        } else if (sysUser.getLoginType() == 2) {
            user.setUnionid_WX(sysUser.getUnionid());
        }*/
        User user = new User();
        user.setPhone(sysUser.getPhone());

        HashMap<String, Object> retMsg = userService.getUserInfo(user);


        ServletContext application = request.getSession().getServletContext();
        application.setAttribute("userId", retMsg.get("id"));

        return ResultFormat.ok(retMsg);
    }

    @GetMapping()
    @ResponseBody
    @ApiOperation("获取个人信息")
    public Result login(HttpServletRequest request) {

        Integer userId = (Integer) request.getSession().getServletContext().getAttribute("userId");
        User user = new User();
        user.setId(userId);
        return ResultFormat.ok(userService.getUserInfo(user));
    }

    @PutMapping()
    @ApiOperation("修改信息")
    public Result putMsg(HttpServletRequest request, User user) {

        Integer userId = (Integer) request.getSession().getServletContext().getAttribute("userId");
        user.setId(userId);
        userService.putUser(user);
        return ResultFormat.ok("update_UserInfo_Success");
    }

    @GetMapping("loginPage")
    @ApiOperation("无权限接口")
    public String loginPage() {

        return "无权限请登陆";
    }
}
